package com.karry.yl.web.interceptor;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.karry.commons.Constants;
import com.karry.commons.util.AESUtil;
import com.karry.commons.vo.Menu;
import com.karry.yl.domain.baseinfo.Organization;
import com.karry.yl.domain.baseinfo.PaymentInfo;
import com.karry.yl.domain.system.Resources;
import com.karry.yl.domain.system.User;
import com.karry.yl.service.baseinfo.OrganizationService;
import com.karry.yl.service.baseinfo.PaymentInfoService;
import com.karry.yl.service.system.LoginService;
import com.karry.yl.service.system.ResourcesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

/**
 * 权限认证拦截器
 */
public class PermissionInterceptor implements HandlerInterceptor {

    @Autowired
    private ResourcesService resourcesService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private OrganizationService organizationService;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(Constants.SK_USER);

        if (null == user) {
            //判断cookie是否有用户信息，如果cookie中有用户名和密码，则根据用户名密码自动登陆
            Cookie[] cookies = request.getCookies();
            String phone = null;
            String password = null;
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals(CookieKey.HUHIJHHIUAUSDGUIASHDJASU.toString())) {
                        //获取用户名
                        phone = AESUtil.decrypt(cookie.getValue(), CookieKey.AGSHIDGDIUAG.toString());
                    }
                    if (cookie.getName().equals(CookieKey.SIOJHSOIOISJAIODOIAJSDO.toString())) {
                        //获取用户名
                        password = AESUtil.decrypt(cookie.getValue(), CookieKey.AGSHIDGDIUAG.toString());
                    }
                }
            }

            //判断phone或者password不等于null
            if (phone != null && password != null) {
                user = loginService.login(phone, password);
                if (null != user && user.getStatus() == 1) {
                    session.setAttribute(Constants.SK_USER, user);    //登陆成功则将用户信息存入session
                    Organization organization = organizationService.selectById(user.getOrgId());
                    session.setAttribute(Constants.SK_JG, organization);    //登陆成功则将机构信息存入session
                    List<Menu> menus = loginService.menus(user.getRoleId());
                    session.setAttribute(Constants.SK_MENUS, menus); //将主页菜单存进session
                    List<Resources> topMenus = loginService.topMenus(user.getRoleId());
                    session.setAttribute(Constants.SK_TOP_MENUS, topMenus); //将主页顶部快速导航菜单存进session
                    Map<String, Resources> resourcesMap = loginService.myResources(user.getRoleId());
                    session.setAttribute(Constants.SK_ALL_RESOURCES, resourcesMap); //将该用户所有权限存进session
                    Map<String, List<String>> pageSubResCode = loginService.myPageResources(user.getRoleId());
                    session.setAttribute(Constants.SK_PAGE_SUB_RES_CODE, pageSubResCode); //将该用户每个页面拥有的操作权限code存进session
                }
            }
        }

        if (null == user) {  //未登录
            response.sendRedirect(request.getContextPath() + "/login");
            return false;
        } else {
            String requestURI = request.getRequestURI();
//            "/user/changepwd","/user/change","/city","/area","/town","/village"
            if (!requestURI.equals("/") && !requestURI.startsWith("/storage/")
                    && !requestURI.equals("/organization/ui/bindPrimary")
                    && !requestURI.equals("/organization/bindPrimary")
                    && !requestURI.equals("/user/changepwd")
                    && !requestURI.equals("/user/change")
                    && !requestURI.equals("/city")
                    && !requestURI.equals("/area")
                    && !requestURI.equals("/town")
                    && !requestURI.equals("/village")
                    && !requestURI.startsWith("/ueditor")
                    && !requestURI.startsWith("/judge")
                    && !requestURI.startsWith("/show")
                    && !requestURI.startsWith("/filing/filingSubmitted")


            ) {
                //左侧菜单
                Map<String, Resources> allResources = (Map<String, Resources>) session.getAttribute(Constants.SK_ALL_RESOURCES);
                Resources resources = allResources.get(requestURI);
                if (null == resources) {
                    //如果没有对应的权限则不允许 访问
                    response.sendError(403);
                    return false;
                }

                if ((resources.getType() == Resources.TYPE_PAGE || resources.getType() == Resources.TYPE_SUB_PAGE) && resources.getUrl().split(",")[0].equals(requestURI)) {
                    request.setAttribute(Constants.RK_CURR_MENU, resources.getParentModule());  //当前模块
                    request.setAttribute(Constants.RK_CURR_PAGE, (resources.getType() == Resources.TYPE_PAGE) ? resources.getCode() : resources.getParentPage());  //当前页面

                    if (resources.getType() == Resources.TYPE_PAGE) {   //如果是主页面，将主页的操作按钮权限信息获取到，用来决定按钮的显示
                        Map<String, List<String>> pageSubResCode = (Map<String, List<String>>) session.getAttribute(Constants.SK_PAGE_SUB_RES_CODE);
                        request.setAttribute(Constants.RK_PAGE_AUTHORIZE, pageSubResCode.get(resources.getCode()));
                    }
                }
            }

            //登录则放过
            return true;
        }
    }
}
